package com.miyake.dsp.osa.lab.wrapper;

import org.apache.commons.lang.ArrayUtils;

import com.miyake.dsp.analyzer.PeakSearch;
import com.miyake.dsp.analyzer.PeakSearchCommon;
import com.miyake.dsp.analyzer.PeakSearchSetting;
import com.miyake.dsp.common.UnitConverter;
import com.miyake.dsp.osa.lab.Calculator;
import com.miyake.dsp.osa.lab.LabUiAnnotation;

@LabUiAnnotation(caption="Peak Search")
public class PeakSearchWrapper extends Calculator {
	public static final String INPUTX = "In-X";
	public static final String INPUTY = "In-Y";
	public static final String INPUT_THRESHOLD = "Threshold";
	public static final String OUTPUTX = "Out-X";
	public static final String OUTPUTY = "Out-Y";
	
	private PeakSearchSetting setting;

	public PeakSearchWrapper(PeakSearchSetting setting) {
		this.setting = setting;
		initInput(INPUTX);
		initInput(INPUTY);
		initInput(INPUT_THRESHOLD);
		initOutput(OUTPUTX);
		initOutput(OUTPUTY);
	}
	
	@Override
	public synchronized void process() {
		if (getInput(INPUT_THRESHOLD) != null) {
			setting.setThreshold(UnitConverter.todB(getInput(INPUT_THRESHOLD).getRealPart()[0]));
		}
//		PeakSearch search = new PeakSearch(setting);
//		search.setSource(getInput(INPUTY));	
//		double[] indexes = search.getProcessed().getRealPart();
		
		PeakSearchCommon peakSearch = new PeakSearchCommon(getInput(INPUTY).getRealPart());
		int[] indexes = ArrayUtils.toPrimitive(peakSearch.getPeakInexes().toArray(new Integer[0]));
		int index;
		
		
		double[] y = null;
		if (this.getInput(INPUTY) != null) {
			y= this.getInput(INPUTY).getRealPart();
		}
		
		double[] x = null;
		if (this.getInput(INPUTX) != null) {
			x = this.getInput(INPUTX).getRealPart();
		}
		else {
			x = new double[y.length];
			for (int i = 0; i < x.length; i++) {
				x[i] = i;
			}
		}
		double[] peakx = new double[indexes.length];
		double[] peaky = new double[indexes.length];
		for (int i = 0; i < indexes.length; i++) {
			index = (int)indexes[i];
			peakx[i] = x[index];
			peaky[i] = y[index];
		}
		this.setOutput(OUTPUTX, peakx);
		this.setOutput(OUTPUTY, peaky);
	}

	@Override
	public Object getSetting() {
		return this.setting;
	}

}
